package com.tentative.competition.schedule.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.extra.mail.MailUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tentative.competition.common.core.domain.entity.SysUser;
import com.tentative.competition.common.core.result.PageResult;
import com.tentative.competition.common.enums.ExamineEnum;
import com.tentative.competition.common.enums.ExamineTypeEnum;
import com.tentative.competition.common.enums.WorksStatusEnum;
import com.tentative.competition.common.model.schedule.param.ScheduleExamineParam;
import com.tentative.competition.common.model.schedule.resp.ScheduleExamineResp;
import com.tentative.competition.common.utils.BeanUtils;
import com.tentative.competition.common.utils.StringUtils;
import com.tentative.competition.schedule.domain.ScheduleExamine;
import com.tentative.competition.schedule.domain.ScheduleWorks;
import com.tentative.competition.schedule.mapper.ScheduleExamineMapper;
import com.tentative.competition.schedule.service.ScheduleExamineService;
import com.tentative.competition.schedule.service.ScheduleMemberInfoService;
import com.tentative.competition.schedule.service.ScheduleWorksService;
import com.tentative.competition.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 管理员审核信息 服务实现类
 * </p>
 *
 * @author SmileH
 * @since 2023-06-22
 */
@Service
public class ScheduleExamineServiceImpl extends ServiceImpl<ScheduleExamineMapper, ScheduleExamine> implements IService<ScheduleExamine>, ScheduleExamineService {


    @Autowired
    private ISysUserService userService;

    @Autowired
    private ScheduleWorksService worksService;

    @Override
    public PageResult<ScheduleExamineResp> selectExamineList(ScheduleExamineParam param) {

        List<Long> userIds = StringUtils.isNotEmpty(param.getName())
                ? userService.selectUserLikeUserName(param.getName())
                : new ArrayList<>();
        List<ScheduleWorks> workIds =
                worksService.lambdaQuery().eq(ScheduleWorks::getDelFlag,0)
                    .like(StringUtils.isNotEmpty(param.getName()),ScheduleWorks::getWorksName,param.getName()).list();
        LambdaQueryWrapper<ScheduleExamine> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ObjUtil.isNotEmpty(param.getExamineType()), ScheduleExamine::getExamineType, param.getExamineType())
                .eq(ObjUtil.isNotEmpty(param.getExamineStatus()), ScheduleExamine::getExamineStatus, param.getExamineStatus())
                .eq(ScheduleExamine::getDelFlag,0);
        if(StringUtils.isNotEmpty(param.getName()) && param.getExamineType().equals(ExamineTypeEnum.ACCOUNT_NUMBER)){
            if(CollUtil.isNotEmpty(userIds)){
                wrapper.in(ScheduleExamine::getUserId,userIds);
            }else{
                wrapper.in(ScheduleExamine::getUserId,Arrays.asList(-1L));
            }
        }

        if(StringUtils.isNotEmpty(param.getName()) && param.getExamineType().equals(ExamineTypeEnum.WORKS)) {
            if (CollUtil.isNotEmpty(workIds)) {
                wrapper.in(ScheduleExamine::getWorksId, workIds);
            } else {
                wrapper.in(ScheduleExamine::getWorksId, Arrays.asList(-1L));
            }
        }
        IPage<ScheduleExamine> iPage = this.page(new Page<>(param.getPageNum(),param.getPageSize()),wrapper);
        PageResult<ScheduleExamineResp> respIPage = new PageResult<>();
        if(CollUtil.isEmpty(iPage.getRecords())){
            return respIPage;
        }
        List<ScheduleExamineResp> resps = new ArrayList<>();
//        List<Long> userIdList = iPage.getRecords().stream().filter(e->e.getUserId() != null && e.getExamineType().equals(ExamineTypeEnum.ACCOUNT_NUMBER))
//                .map(ScheduleExamine::getUserId).collect(Collectors.toList());
        List<Long> workIdList = iPage.getRecords().stream().filter(e->e.getWorksId() != null && e.getExamineType().equals(ExamineTypeEnum.WORKS))
                .map(ScheduleExamine::getWorksId).collect(Collectors.toList());
        List<SysUser> users = userService.selectInIds(null);
        Map<Long,SysUser> userMap = CollUtil.isNotEmpty(users) ? users.stream().collect(Collectors.toMap(SysUser::getUserId, Function.identity())) : new HashMap<>();
        List<ScheduleWorks> works = CollUtil.isNotEmpty(workIdList) ? worksService.lambdaQuery()
                .eq(ScheduleWorks::getDelFlag,0).in(ScheduleWorks::getId,workIdList).list() : new ArrayList<>();
        Map<Long,ScheduleWorks> workMap = CollUtil.isNotEmpty(works) ?
                works.stream().collect(Collectors.toMap(ScheduleWorks::getId,Function.identity())) : new HashMap<>();
        for (ScheduleExamine record : iPage.getRecords()) {
            SysUser user = userMap.containsKey(record.getUserId()) ? userMap.get(record.getUserId()) : new SysUser();
            ScheduleWorks work = workMap.containsKey(record.getWorksId()) ? workMap.get(record.getWorksId()) : new ScheduleWorks();
            ScheduleExamineResp resp = BeanUtils.copyBean(record,ScheduleExamineResp.class);
            if(record.getExamineType().equals(ExamineTypeEnum.ACCOUNT_NUMBER)){
                resp.setUserName(user.getUserName());
                resp.setName(user.getNickName());
                resp.setPhonenumber(user.getPhonenumber());
                resp.setEmail(user.getEmail());
            }else{
                resp.setUserName(userMap.get(work.getUserId()).getUserName());
                resp.setName(work.getWorksName());
            }
            resps.add(resp);
        }

        PageResult<ScheduleExamineResp> pageResult = new PageResult<ScheduleExamineResp>();
        pageResult.setContent(resps);
        pageResult.setTotal(iPage.getTotal());
        return pageResult;
    }

    /**
     * 审核通过
     * @param param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean agree(ScheduleExamineParam param) {
        //查询审批数据
        List<ScheduleExamine> examineList = lambdaQuery()
                .in(CollUtil.isNotEmpty(param.getIds()), ScheduleExamine::getId, param.getIds())
//                .eq(ScheduleExamine::getExamineStatus,ExamineEnum.US_APPROVE)
                .eq(ScheduleExamine::getDelFlag,0)
                .list();
        if (CollUtil.isEmpty(examineList)){
            throw new RuntimeException("没有找到需要审核的数据！");
        }
        //作品审批
        List<ScheduleExamine> worksList = examineList.stream().filter(x -> ExamineTypeEnum.WORKS.equals(x.getExamineType())).collect(Collectors.toList());
        Set<Long> worksIds = worksList.stream().map(ScheduleExamine::getWorksId).collect(Collectors.toSet());
        if (CollUtil.isNotEmpty(worksIds)){
            List<ScheduleWorks> scheduleWorks = worksService.lambdaQuery()
                    .in(ScheduleWorks::getId, worksIds)
                    .eq(ScheduleWorks::getDelFlag, 0)
                    .list();
            scheduleWorks.forEach(x->{
                x.setWorksStatus(WorksStatusEnum.APPROVAL_PASS);
            });
            worksService.saveOrUpdateBatch(scheduleWorks);
            //准备发邮件
            Set<Long> userIds = scheduleWorks.stream().map(ScheduleWorks::getUserId).collect(Collectors.toSet());
            List<SysUser> sysUsers = userService.lambdaQuery().in(SysUser::getUserId, userIds).eq(SysUser::getDelFlag,"0").list();
            sysUsers.forEach(x->MailUtil.send(x.getEmail(), "作品审核通知", "您提交的作品信息，审核已通过，请及时关注赛事动态！", false));
        }
        //账号审批
        List<ScheduleExamine> accountNumberList = examineList.stream().filter(x -> ExamineTypeEnum.ACCOUNT_NUMBER.equals(x.getExamineType())).collect(Collectors.toList());
        Set<Long> userIds = accountNumberList.stream().map(ScheduleExamine::getUserId).collect(Collectors.toSet());
        if (CollUtil.isNotEmpty(userIds)){
            List<SysUser> sysUsers = userService.lambdaQuery().in(SysUser::getUserId, userIds).eq(SysUser::getDelFlag,"0").list();
            sysUsers.forEach(x->{
                x.setStatus("0");
                userService.updateUser(x);
            });
            //准备发送邮件
            sysUsers.forEach(x->MailUtil.send(x.getEmail(), "账号审核通知", "您注册的账号信息，审核已通过，请尽快上传作品！", false));
        }
        //修改审批数据
        examineList.forEach(x->{
            x.setExamineStatus(ExamineEnum.ALREADY_APPROVE);
            x.setExamineTime(new Date());
        });
        this.saveOrUpdateBatch(examineList);
        return true;
    }

    /**
     * 审核拒绝
     * 账号拒绝只需要发送邮件
     * 作品拒绝，打回草稿状态
     * @param param
     * @return
     */
    @Override
    public boolean refuse(ScheduleExamineParam param) {
        //查询审批数据
        List<ScheduleExamine> examineList = lambdaQuery()
                .in(CollUtil.isNotEmpty(param.getIds()), ScheduleExamine::getId, param.getIds())
                .eq(ScheduleExamine::getExamineStatus,ExamineEnum.US_APPROVE)
                .eq(ScheduleExamine::getDelFlag,0)
                .list();
        if (CollUtil.isEmpty(examineList)){
            throw new RuntimeException("没有找到需要审核的数据！");
        }
        //作品审批
        List<ScheduleExamine> worksList = examineList.stream().filter(x -> ExamineTypeEnum.WORKS.equals(x.getExamineType())).collect(Collectors.toList());
        Set<Long> worksIds = worksList.stream().map(ScheduleExamine::getWorksId).collect(Collectors.toSet());
        if (CollUtil.isNotEmpty(worksIds)){
            List<ScheduleWorks> scheduleWorks = worksService.lambdaQuery()
                    .in(ScheduleWorks::getId, worksIds)
                    .eq(ScheduleWorks::getDelFlag, 0)
                    .list();
            scheduleWorks.forEach(x->x.setWorksStatus(WorksStatusEnum.DRAFT));
            worksService.saveOrUpdateBatch(scheduleWorks);
            //准备发邮件
            Set<Long> userIds = scheduleWorks.stream().map(ScheduleWorks::getUserId).collect(Collectors.toSet());
            List<SysUser> sysUsers = userService.lambdaQuery().in(SysUser::getUserId, userIds).eq(SysUser::getDelFlag,"0").list();
            sysUsers.forEach(x->MailUtil.send(x.getEmail(), "作品审核通知", "您提交的作品信息，审核拒绝，拒绝原因："+param.getRefuseReason(), false));
        }
        //账号审批
        List<ScheduleExamine> accountNumberList = examineList.stream().filter(x -> ExamineTypeEnum.ACCOUNT_NUMBER.equals(x.getExamineType())).collect(Collectors.toList());
        Set<Long> userIds = accountNumberList.stream().map(ScheduleExamine::getUserId).collect(Collectors.toSet());
        if (CollUtil.isNotEmpty(userIds)){
            List<SysUser> sysUsers = userService.lambdaQuery().in(SysUser::getUserId, userIds).eq(SysUser::getDelFlag,"0").list();
            //准备发送邮件
            sysUsers.forEach(x->MailUtil.send(x.getEmail(), "账号审核通知", "您注册的账号信息，审核拒绝，如需帮助，请联系首页管理员！", false));
        }
        //修改审批数据
        examineList.forEach(x->{
            x.setExamineStatus(ExamineEnum.REFUSE_APPROVE);
            x.setExamineTime(new Date());
        });
        return this.saveOrUpdateBatch(examineList);
    }
}
